package com.xiemu.ironman.core.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class FileUtils {

    public static boolean creteFilePath(String tempFileName) {
        File file = new File(tempFileName);
        if (!file.getParentFile().exists()) {
            boolean createParent = file.getParentFile().mkdirs();
            if (!createParent) {
                throw new IllegalStateException("create error parent file temp dir failed");
            }
        }

        if (!file.exists()) {
            //创建文件
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new IllegalStateException("create error "+tempFileName+" file  failed,e="+e.getMessage());
            }
        }
        return true;
    }

    public static String write(MultipartFile upload, String path) throws IOException {

        // 上传文件唯一名修改
        String filename = upload.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid + "_" + filename;

        creteFilePath(path+filename);
        // 文件保存
        upload.transferTo(new File(path, filename));
        return filename;
    }
}
